/**
 *
 */
package com.darren.befriend;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.darren.befriend.constants.Constant;
import com.darren.befriend.fragments.ChatFragment;
import com.darren.befriend.fragments.FilmFragment;
import com.darren.befriend.fragments.FriendForFragment;
import com.darren.befriend.fragments.FriendsFragment;
import com.darren.befriend.fragments.InterestFragment;
import com.darren.befriend.fragments.MusicFragment;
import com.darren.befriend.fragments.PersonalityFragment;
import com.darren.befriend.fragments.SportsFragment;
import com.darren.befriend.fragments.HobbyBaseFragment.checkHobiesListener;
import com.darren.befriend.fragments.HomeFragment;
import com.darren.befriend.fragments.ProfileFragment;
import com.darren.befriend.fragments.SearchFilterFragment;
import com.darren.befriend.fragments.SettingsFragment;
import com.darren.befriend.fragments.ProfileBaseFragment.OnRelationshipChanged;
import com.darren.befriend.fragments.SettingsFragment.OnSettingClickListener;
import com.darren.befriend.fragments.UserSettingFragment;
import com.darren.befriend.models.HobbyModel;
import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.utilities.MySharedPreferences;
import com.darren.befriend.utilities.Utilities;
import com.darren.befriend.views.CircleImageView;
import com.parse.ParseObject;
import com.parse.ParseUser;

/**
 * @author ubuntu
 * 
 */
public class HomeActivity extends BaseActivity implements OnClickListener,
		OnSettingClickListener, checkHobiesListener, OnItemClickListener,
		com.darren.befriend.fragments.UniversityFragment.OnUniversitySelected,
		OnRelationshipChanged {

	private boolean isLock = false, isExit = false;
	private Fragment mContent;
	private ImageView mLeftButton;
	private ImageView mRightButton;
	private FragmentTransaction ft;
	private FragmentTransaction ft1;
	private TextView mHeaderTitle;
	private ImageView mTopLogo;
	private FragmentManager mFragmentManager;
	private String FRAGMENT_TAG = "fragment";
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private ParseUser mCurrentUser;
	private ArrayList<ParseUser> mFriends;

	public void setLock(boolean isLock) {
		this.isLock = isLock;
	}

	public Fragment getContent() {
		return mContent;
	}

	public void setContent(Fragment mContent) {
		this.mContent = mContent;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (savedInstanceState != null) {

			mContent = getSupportFragmentManager().getFragment(
					savedInstanceState, "mContent");
		}

		mCurrentUser = getCurrentUser();
		mFriends = new ArrayList<ParseUser>();
		if (mContent == null) {

			mContent = HomeFragment.makeInstance();
		}

		setContentView(R.layout.layout_home);
		String[] colors = getResources().getStringArray(R.array.menu_items);
		int[] resId = new int[] { R.drawable.icon_home, R.drawable.icon_home,
				R.drawable.icon_friend, R.drawable.icon_setting };
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		SlidingMenuItemAdapter menuAdapter = new SlidingMenuItemAdapter(this,
				colors, resId);
		mDrawerList.setAdapter(menuAdapter);
		mDrawerList.setOnItemClickListener(this);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.icon_menu, R.string.a_friend_for,
				R.string.a_friend_for) {
			public void onDrawerClosed(View view) {

				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {

				invalidateOptionsMenu();
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);
		mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

		mLeftButton = (ImageView) findViewById(R.id.header_left_btn);
		mLeftButton.setImageResource(R.drawable.icon_menu);
		mLeftButton.setOnClickListener(this);

		mRightButton = (ImageView) findViewById(R.id.header_right_btn);
		mRightButton.setImageResource(R.drawable.icon_search);
		mRightButton.setOnClickListener(this);
		mHeaderTitle = (TextView) findViewById(R.id.header_title_txt);

		mTopLogo = (ImageView) findViewById(R.id.header_title_img);
		mTopLogo.setImageResource(R.drawable.top_logo);

		// for the first time
		mFragmentManager = getSupportFragmentManager();
		ft1 = mFragmentManager.beginTransaction();
		ft1.replace(R.id.fragment_initation_content, mContent, FRAGMENT_TAG);
		ft1.addToBackStack(null);
		ft1.commit();
	}

	public ArrayList<ParseUser> getFriendsList() {

		return mFriends;
	}

	public void setFriendList(ArrayList<ParseUser> friendList) {

		if (mFriends != null) {

			mFriends = friendList;
		}
	}

	/**
	 * show/hide right button
	 * 
	 * @param isShow
	 */
	public void showRightButtonImg(boolean isShow) {

		if (isShow) {

			mRightButton.setVisibility(View.VISIBLE);
		} else {

			mRightButton.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * set right button image
	 * 
	 * @param resId
	 */
	public void setRightImage(int resId) {

		if (mRightButton != null) {

			mRightButton.setImageResource(resId);
		}
	}

	/**
	 * set left button image
	 * 
	 * @param resId
	 */
	public void setLeftImage(int resId) {

		if (mLeftButton != null) {

			mLeftButton.setImageResource(resId);
		}
	}

	/**
	 * change fragment
	 * 
	 * @param fragment
	 */
	public void switchContent(Fragment fragment) {

		closeNavigation();
		mContent = fragment;
		ft = mFragmentManager.beginTransaction();
		ft.replace(R.id.fragment_initation_content, fragment, FRAGMENT_TAG);
		ft.addToBackStack(null);
		ft.commit();
	}

	public void switchContentWithNormalAnimation(Fragment fragment) {

		mContent = fragment;
		ft = mFragmentManager.beginTransaction();
		ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out,
				R.anim.slide_right_in, R.anim.slide_right_out);
		ft.replace(R.id.fragment_initation_content, fragment, FRAGMENT_TAG);
		ft.addToBackStack(null);
		ft.commit();
	}

	/**
	 * changr content of activity
	 * 
	 * @param fragment
	 */
	public void switchContentWithAnimation(Fragment fragment) {

		mContent = fragment;
		ft = mFragmentManager.beginTransaction();
		ft.setCustomAnimations(R.anim.slide_down_in, 0);
		ft.replace(R.id.fragment_initation_content, fragment, FRAGMENT_TAG);
		ft.addToBackStack(null);
		ft.commit();
	}

	public void showTopLogo() {

		if (mTopLogo != null) {

			mTopLogo.setVisibility(View.VISIBLE);
		}
		if (mHeaderTitle != null) {

			mHeaderTitle.setVisibility(View.GONE);
		}
	}

	public void setActivityTitle(String title) {

		if (mHeaderTitle != null) {

			mHeaderTitle.setVisibility(View.VISIBLE);
			mHeaderTitle.setText(title);
		}

		if (mTopLogo != null) {

			mTopLogo.setVisibility(View.GONE);
		}
	}

	private void closeNavigation() {

		if (mDrawerLayout.isDrawerVisible(Gravity.LEFT)) {

			mDrawerLayout.closeDrawer(Gravity.LEFT);
		}
	}

	private void displayNavigation() {

		if (mDrawerLayout.isDrawerVisible(Gravity.LEFT)) {

			mDrawerLayout.closeDrawer(Gravity.LEFT);
		} else {

			mDrawerLayout.openDrawer(Gravity.LEFT);
		}
	}

	@Override
	public void onClick(View v) {

		if (isLock) {

			return;
		}

		switch (v.getId()) {

		case R.id.header_left_btn:
			if (mContent instanceof HomeFragment
					|| mContent instanceof SettingsFragment
					|| mContent instanceof FriendsFragment
					|| mContent instanceof ProfileFragment) {
				displayNavigation();
			} else {

				if (mContent instanceof FilmFragment) {

					((FilmFragment) mContent).saveSettingItems(Constant.FILM);
				} else if (mContent instanceof SportsFragment) {

					((SportsFragment) mContent)
							.saveSettingItems(Constant.SPORT);
				} else if (mContent instanceof InterestFragment) {

					((InterestFragment) mContent)
							.saveSettingItems(Constant.INTEREST);
				} else if (mContent instanceof MusicFragment) {

					((MusicFragment) mContent).saveSettingItems(Constant.MUSIC);
				} else if (mContent instanceof FriendForFragment) {

					((FriendForFragment) mContent)
							.saveSettingItems(Constant.HOBBY);
				} else if (mContent instanceof PersonalityFragment) {

					((PersonalityFragment) mContent)
							.saveSettingItems(Constant.PERSONALITY);
				} else {

					FriendsFragment.needToReloadList = false;
					Utilities.hideKeyboard(HomeActivity.this);
					mFragmentManager.popBackStackImmediate();
					mContent = mFragmentManager.findFragmentByTag(FRAGMENT_TAG);
				}
			}
			break;
		case R.id.header_right_btn:
			if (mContent instanceof HomeFragment) {

				HomeFragment.mFriendArr = null;
				mContent = SearchFilterFragment.create(mCurrentUser);
				switchContentWithNormalAnimation(mContent);
			} else if (mContent instanceof ProfileFragment) {

				mContent = UserSettingFragment.create();
				switchContentWithNormalAnimation(mContent);
			} else if (mContent instanceof ChatFragment) {

				((ChatFragment) mContent).showInfoLayout();
			}

			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {

		if (isExit) {

			super.onBackPressed();
		} else {

			if (mDrawerLayout.isDrawerVisible(Gravity.LEFT)) {

				mDrawerLayout.closeDrawer(Gravity.LEFT);
			} else {

				removeFragmentFromStack();
			}
		}
	}

	public void removeFragmentFromStack() {
		if (mFragmentManager.getBackStackEntryCount() > 1) {

			mFragmentManager.popBackStackImmediate();
			mContent = mFragmentManager.findFragmentByTag(FRAGMENT_TAG);
		} else {

			isExit = true;
			onBackPressed();
		}
	}

	@Override
	public void onClickItem(int position) {
		if (position == 0) {

			Intent shareIntent = new Intent();
			shareIntent.setAction(Intent.ACTION_SEND);
			shareIntent.putExtra(Intent.EXTRA_EMAIL,
					new String[] { getString(R.string.contact_email) });
			shareIntent.putExtra(Intent.EXTRA_SUBJECT,
					getString(R.string.contact));
			shareIntent.setType("text/html");
			startActivity(Intent.createChooser(shareIntent,
					getString(R.string.contact_email_choser)));
		} else if (position == 1) {

			mParseUser.put("Status", false);
			try {

				ParseObject meInfo = mParseUser.getParseObject("MeInfo");
				ParseObject filter = mParseUser.getParseObject("Filter");
				meInfo.saveInBackground();
				filter.saveInBackground();
				mParseUser.saveInBackground();
			} catch (Exception e) {
				// TODO Auto-generated catch block

			}

			ParseUser.logOut();
			MySharedPreferences.setPreferences(
					MySharedPreferences.PREF_USERNAME, "");
			MySharedPreferences.setPreferences(
					MySharedPreferences.PREF_PASSWORD, "");
			FriendsFragment.mFriendList = null;
			HomeFragment.mFriendArr = null;
			FriendsFragment.requestArray = null;
			Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
			startActivity(intent);
			finish();
		}
	}

	@Override
	public void onClickCheckHobies(int type, ArrayList<HobbyModel> selectedItems) {
		if (selectedItems != null) {
			ArrayList<Boolean> arr = new ArrayList<Boolean>();
			for (int i = 0; i < selectedItems.size(); i++) {

				if (!selectedItems.get(i).isEmpty) {

					arr.add(selectedItems.get(i).isSelected);
				}
			}

			if (type == Constant.INTEREST) {

				mParseUser.put("INTEREST", arr);
			} else if (type == Constant.SPORT) {

				mParseUser.put("SPORTS", arr);
			} else if (type == Constant.FILM) {

				mParseUser.put("FILMS", arr);
			} else if (type == Constant.MUSIC) {

				mParseUser.put("MUSIC", arr);
			} else if (type == Constant.HOBBY) {

				ParseObject meInfo = (ParseObject) mParseUser.get("MeInfo");
				if (meInfo != null) {

					meInfo.put("Hobby", arr);
				}
			} else if (type == Constant.PERSONALITY) {

				ParseObject filter = (ParseObject) mParseUser.get("Filter");
				if (filter != null) {

					filter.put("Personality", arr);
				}
			}

			try {

				mParseUser.saveInBackground();
				mFragmentManager.popBackStackImmediate();
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
	}

	@Override
	public void onClickSkip() {

		mFragmentManager.popBackStackImmediate();
	}

	private class SlidingMenuItemAdapter extends BaseAdapter {

		private Context mContext;
		private String[] mItemArr;
		private int[] mResArr;

		public SlidingMenuItemAdapter(Context c, String[] itemArr, int[] resId) {

			mContext = c;
			mItemArr = itemArr;
			mResArr = resId;
		}

		@Override
		public int getCount() {

			return mItemArr.length;
		}

		@Override
		public Object getItem(int arg0) {

			return null;
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View item;
			MenuItemHoder holder = null;
			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if (convertView == null) {
				holder = new MenuItemHoder();
				item = inflater.inflate(R.layout.layout_sliding_menu_item,
						parent, false);
				holder.iconMenu = (ImageView) item
						.findViewById(R.id.sliding_icon);
				holder.titleMenu = (TextView) item
						.findViewById(R.id.sliding_title);
				Utilities.setFontType(mContext, holder.titleMenu);
				holder.notificationMenu = (TextView) item
						.findViewById(R.id.sliding_notification);
				holder.meIcon = (CircleImageView) item
						.findViewById(R.id.sliding_icon_circle);
				Utilities.setFontType(mContext, holder.notificationMenu);
				item.setTag(holder);
			} else {

				item = (View) convertView;
				holder = (MenuItemHoder) item.getTag();
			}

			holder.titleMenu.setText(mItemArr[position]);
			if (position == 0) {

				getUserImage(mCurrentUser, holder.meIcon);
				holder.meIcon.setVisibility(View.VISIBLE);
				holder.iconMenu.setVisibility(View.INVISIBLE);
			} else {

				holder.meIcon.setVisibility(View.INVISIBLE);
				holder.iconMenu.setVisibility(View.VISIBLE);
				holder.iconMenu.setImageResource(mResArr[position]);
			}

			return item;
		}

		class MenuItemHoder {
			ImageView iconMenu, meIcon;
			TextView titleMenu;
			TextView notificationMenu;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		Fragment newContent = null;
		switch (position) {
		case 0:

			newContent = ProfileFragment.makeInstance(mCurrentUser);
			break;
		case 1:

			newContent = HomeFragment.makeInstance();
			break;
		case 2:

			FriendsFragment.needToReloadList = true;
			newContent = FriendsFragment.makeInstance();
			break;
		case 3:

			newContent = SettingsFragment.create();
			break;
		}

		if (newContent != null) {

			switchContent(newContent);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.darren.befriend.fragments.UserSettingFragment.OnUniversitySelected
	 * #onUserniverSelected(java.lang.String)
	 */
	@Override
	public void onUserniverSelected(int selectedUniver) {
		// TODO Auto-generated method stub

		ParseObject meInfo = (ParseObject) mParseUser.get("MeInfo");
		if (meInfo != null) {

			meInfo.put("University", selectedUniver);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.darren.befriend.fragments.ProfileBaseFragment.OnRelationshipChanged
	 * #relationshipChanged(com.parse.ParseUser)
	 */
	@Override
	public void relationshipChanged(ParseUser user) {
		// TODO Auto-generated method stub

		HomeFragment.updateFriendList(user);
	}

	private void getUserImage(ParseUser user, ImageView view) {

		String userImage = "";
		try {

			String fullName = user.get("fullName").toString();
			if (!fullName.contains("_local")) {

				userImage = String.format(
						getResources().getString(R.string.profile_url),
						user.getUsername());
			} else {

				try {

					byte[] image = (byte[]) user.get("Photo");
					Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0,
							image.length);
					view.setImageBitmap(bitmap);
					return;
				} catch (Exception e) {

					view.setImageResource(R.drawable.tmp_full_pic);
					return;
				}
			}
		} catch (Exception ex) {

			LogUtil.e("getUserImage()", "getUserImage");
		}

		mImageLoader.displayImage(userImage, view, mOptions);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		LogUtil.e("Home acitivity", "onDestroy");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		LogUtil.e("Home acitivity", "onStop");
		try {

			LogUtil.e("Save data", "Save data when back");
			mParseUser.put("Status", false);
			mParseUser.saveInBackground();
			ParseObject meInfo1 = mParseUser.getParseObject("MeInfo");
			ParseObject filter1 = mParseUser.getParseObject("Filter");
			meInfo1.saveInBackground();
			filter1.saveInBackground();
		} catch (Exception e) {
			// TODO Auto-generated catch block

		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		LogUtil.e("Home acitivity", "onStart");
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		LogUtil.e("Home acitivity", "onPause");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		LogUtil.e("Home acitivity", "onResume");
	}
}
